<?php

namespace App\Http\Controllers;

use App\Http\Common\JWT;
use App\Models\AdminUser;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{

    public function __construct()
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:OPTIONS,POST,GET,PUT,DELETE');
        header('Access-Control-Allow-Headers:requesttype,x-requested-with,content-type,authorization,x-csrf-token,origin,x-custom-header');
    }

    public function makeResponse($data = [], $msg = '', $code = 500)
    {
        return compact('code', 'msg', 'data');
    }

    public function return_json($code, $data, $msg)
    {
        $data = ['code' => $code, 'data' => $data, 'msg' => $msg];
        return response()->json($data);
    }

    public function assoc_unique($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
//        sort($arr); //sort函数对数组进行排序
        return $arr;
    }

    function array_group_by($arr, $key)
    {
        $grouped = array();
        foreach ($arr as $value) {
            $grouped[$value[$key]][] = $value;
        }
        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $parms = array_merge($value, array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('array_group_by', $parms);
            }
        }
        return $grouped;
    }

    public function searchmax($arr, $field) // 最小值 只需要最后一个max函数  替换为 min函数即可
    {
        if (!is_array($arr) || !$field) { //判断是否是数组以及传过来的字段是否是空
            return false;
        }

        $temp = array();
        foreach ($arr as $key => $val) {
            $temp[] = $val[$field]; // 用一个空数组来承接字段
        }
        return max($temp);  // 用php自带函数 max 来返回该数组的最大值，一维数组可直接用max函数
    }

    public function checkToken($request)
    {
        $request = new \Illuminate\Http\Request();
        $header = $request->header();

        if (!$header) {
            return $this->makeResponse([], '登录失效!', 401);
        };
        $token = substr($header, 7);

        $jwtToken = JWT::verifyToken($token);

        if ($jwtToken['jti'] !== env('JWT_CODE')) {
            return $this->makeResponse([], '签名错误', 500);
        } else {
            $user = AdminUser::where(['username' => $jwtToken['name']])->first()->toArray();
            $status = passwordVerify($jwtToken['pass'], $user['password']);
            unset($user['password']);

            if ($status) {
                return $user;

            } else {
                return $this->makeResponse([], 'Token验证失败~', 500);
            }

        }

    }

    public function getUserInfo($request)
    {
        $data = $this->checkToken($request);
        return $data;
    }

    public static function createSn($type = 1)
    {
        $danhao = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        if ($type == 'z' || $type == 'Z') {
            return 'Z' . $danhao;
        }
        return $danhao;
    }

    function isCreditNo($vStr)
    {
        $vCity = array(
            '11', '12', '13', '14', '15', '21', '22',
            '23', '31', '32', '33', '34', '35', '36',
            '37', '41', '42', '43', '44', '45', '46',
            '50', '51', '52', '53', '54', '61', '62',
            '63', '64', '65', '71', '81', '82', '91'
        );
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17; $i >= 0; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
            }
            if ($vSum % 11 != 1) return false;
        }
        return true;
    }
    public function getTree($data, $pId)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pId) { //父亲找到儿子
                $v['zi'] = $this->getTree($data, $v['id']);
                $tree[] = $v;
//                unset($data[$k]);
            }
        }
        return $tree;
    }
    function getDistance($slng, $slat, $elng, $elat,$decimal=2){

        $earth_radius = 6378.137;//地球半径
        $lng1 = (M_PI / 180) * $slng;
        $lng2 = (M_PI / 180) * $elng;
        $lat1 = (M_PI / 180) * $slat;
        $lat2 = (M_PI / 180) * $elat;
        // 两点间距离 km，如果想要米的话，结果*1000就可以了
        $d = acos(
                sin($lat1) * sin($lat2)
                + cos($lat1) * cos($lat2) * cos($lng2 - $lng1)
            ) * $earth_radius;
        // 精度2位小数
        $d = round($d,$decimal);

        return $d;

    }
}
